package com.jushu.storbox.util.identity;

import com.jushu.storbox.util.LogUtil;

public abstract class AbsIdentity {
	
	protected final static int BUFFER_SIZE = 1024 * 64;
	
	protected final String TAG = AbsIdentity.class.getSimpleName();

	protected String identity = "";
	
	protected IidentityCallback IdentityCallback = null;
	
	final protected IidentityCallback defaultCallback = new IidentityCallback() {

		@Override
		public void onStart() {
			LogUtil.i(TAG,"onStart...");
		}

		@Override
		public void onProgress(int currentProgress, long currentSize,
				long maxSize) {
			LogUtil.i(TAG,"onProgress...");
		}

		@Override
		public void onFailure(Throwable t) {
			LogUtil.i(TAG,"onFailure...:" + t.getMessage());
		}

		@Override
		public void onSuccess(String identity) {
			LogUtil.i(TAG,"onSuccess("+identity+")");
		}

	};

	protected void setIdentityCallback(IidentityCallback callback) {
		if (null == callback) {
			IdentityCallback = defaultCallback;
		} else {
			IdentityCallback = callback;
		}
	}
	
	public final String computeIdentity() {
		IdentityCallback.onStart();
		try {
			identity = doComputeIdentity();
			IdentityCallback.onSuccess(identity);
		} catch (OutOfMemoryError e) {
			LogUtil.e(TAG, e.getMessage());
			IdentityCallback.onFailure(e.fillInStackTrace());
		} catch (Exception e) {
			LogUtil.e(TAG, e.getMessage());
			IdentityCallback.onFailure(e.fillInStackTrace());
		} 
	
		return identity;
	}

	protected abstract String doComputeIdentity() throws Exception ;

	protected String byte2hex(byte[] buffer) {
		if(buffer == null) {
			throw new IllegalArgumentException("byte buffer is null");
		}
		
		StringBuffer hs = new StringBuffer(buffer.length);
		String stmp = "";
		int len = buffer.length;
		for (int n = 0; n < len; n++) {
			stmp = Integer.toHexString(buffer[n] & 0xFF);
			if (stmp.length() == 1)
				hs = hs.append("0").append(stmp);
			else {
				hs = hs.append(stmp);
			}
		}
		return String.valueOf(hs);
	}

	protected String bytes2String(byte[] buffer) {
		if(buffer == null) {
			throw new IllegalArgumentException("byte buffer is null");
		}
		char hexDigits[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
		char[] temp = new char[buffer.length * 2];
		for( int i=0; i < buffer.length; i++) {
			byte b = buffer[i];
			temp[i * 2 + 0] = hexDigits[b >>> 4 & 0x0f];
			temp[i * 2 + 1] = hexDigits[b & 0x0f];
		}
		return String.valueOf(temp);
	}
	
	protected int copy(final byte[] inBuff, byte[] outBuff) {
		if(inBuff == null) {
			throw new IllegalArgumentException("in buffer is null");
		}
		
		if(outBuff == null) {
			throw new IllegalArgumentException("out buffer is null");
		}
		
		if(outBuff.length >= inBuff.length ){
			for(int i=0; i<inBuff.length; i++){
				outBuff[i] = inBuff[i];
			}
			return inBuff.length;
		} else {
			for(int i=0; i<outBuff.length; i++){
				outBuff[i] = inBuff[i];
			}
			return outBuff.length;
		}
	}
}
